import random
import mysql.connector

config = {
    'host': "1.1.1.1",
    'user': 'root',
    'password': '***********',
    'database': 'school_db',
    'charset': 'utf8mb4',
    'collation': 'utf8mb4_unicode_ci',
    'port': 3306
}

def connect_to_database():
    """连接到数据库"""
    try:
        conn = mysql.connector.connect(**config)
        return conn
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("错误的用户名和密码")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("数据库不存在，正在尝试创建")
            create_database()
            return connect_to_database()
        else:
            print(err)
        return None

def update_student_scores():
    conn = connect_to_database()
    if not conn:
        return
    cursor = conn.cursor()
    cursor.execute("SELECT id FROM students")
    student_ids = [row[0] for row in cursor.fetchall()]


    for student_id in student_ids:
        chinese_score = round(random.uniform(60, 100), 2)
        math_score = round(random.uniform(60, 100), 2)
        english_score = round(random.uniform(60, 100), 2)

        update_sql = """
        UPDATE students
        SET chinese_score = %s, math_score = %s, english_score = %s
        WHERE id = %s
        """
        cursor.execute(update_sql, (chinese_score, math_score, english_score, student_id))

    conn.commit()

def main():
    conn = connect_to_database()
    if conn:
        update_student_scores()
        conn.close()

if __name__ == "__main__":
    main()